var APP = require("../main/app");
var REFRESH = require("../other/refresh");
/**
 * 数据列表类
 * @type {Object}
 */
module.exports = {
	page:1,
    pageHas:true,
    obj: null,
	result:false,
	isscrolltobottom:false,//是否在下拉刷新
	reset:true,//可以重置
    defaultEmptyHtml:'<div class="empty-box"><p>暂无数据</p></div>',
    defaultEmptyHtml2:'<div class="empty-box"><p>No data</p></div>',
    /**
     * obj
     * api:接口名称
     * params:请求参数
     * emptyHtml:数据为空的展示
     * pageSize:每页显示数量
     * render:模板对象，传入obj对象，例如var listTpl=require('./list')，则将listTpl传入
     * renderBox:数据装载容器
     * dataChildKey:json对象子数组，如果对象为data返回的不传入，例如res.data.list则传入'list'
     * headRefresh:是否头部加载刷新 =1加载
     * formatKey是否需要序列化
	 * debug 值为empty数据为空显示
	 * isCallback 是否回调all每次回调,one第一次回调
	 * success 回调函数
	 * renderExtraData 数据对象，附加到模板
	 * switchKey 示例list=works，比如共用一个模板A模板给出的是data.works，B模板给出的是data.list，模板中只能存在一个则A模板，需要转换数据data.list=data.works
     * @type {Object}
	 * multistageChildKey dataChildKey 多级处理 比如'list.songs',
     */
	init: function(obj,callback) {
		var that = this;
		if(!obj.emptyHtml) {
			let lang =  api.getGlobalData({key: 'lang'}) || 'cn';
			if(lang == 'cn'){
				obj.emptyHtml = this.defaultEmptyHtml;
			}else{
				obj.emptyHtml = this.defaultEmptyHtml2;
			}
        }
        if(!obj.pageSize) {
        	obj.pageSize = 10;
        }
        that.obj = obj;
		if(obj.page){
			this.page = obj.page ? obj.page : this.page;
		}
		this.pageHas = true;
		this.getData(callback);
		//当滚动到底部
        api.addEventListener({
            name:'scrolltobottom',
            extra:{
                threshold:0            //设置距离底部多少距离时触发，默认值为0，数字类型
            }
        }, function(ret, err){ 
			if(that.result){
				that.isscrolltobottom = true;
				$('.mescroll-upwarp').show();
				that.getData();
			}
        });
        //判断是否有下拉刷新
        if(obj.headRefresh==1) {
            that.listenHeaderRefresh();
        }
	},
	getData: function(callback) {
		var that = this;
        this.obj.params.page = this.page;
		this.obj.params.limit_num = this.obj.pageSize ? this.obj.pageSize : 10; 
        // console.log('数据：' +JSON.stringify(this.obj.params));
		that.result = false;
        if(this.pageHas==true) {
        	APP.r.get({
        		api: this.obj.api,
        		params : this.obj.params,
        		success : function(ret) {
					// console.log('ret:'+ JSON.stringify(ret))
					// 返回数据
					that.render(ret);
	                if(that.obj.headRefresh==1) {
	                    //api.refreshHeaderLoadDone();
	                }
        		}
        	})
        }
	},
	render:function(ret) {
        this.result = false;
		this.isscrolltobottom = false;
		this.reset = true;
		
		$('.mescroll-upwarp').hide();//隐藏上拉加载
		if(this.obj.debug == 'empty') {
			if(this.obj.dataChildKey) {
			    ret.data[this.obj.dataChildKey] = [];
			} else {
			    ret.data = [];
			}
		}
		//如果有添加到模板的其他变量
		if(this.obj.renderExtraData) {
			$.extend(ret,this.obj.renderExtraData);
		}
		
		var dataArray = ret.data;
		//如果有switchKey
		if(this.obj.switchKey) {
			var switchKeyArr = this.obj.switchKey.split('=');
			if(switchKeyArr.length==2) {
				ret.data[switchKeyArr[0]] = ret.data[switchKeyArr[1]];
				// console.log("BBBB"+JSON.stringify(ret.data));
			}
		}
        //如果有子项
		
		if(this.obj.multistageChildKey && this.obj.dataChildKey){
			var strs= new Array(); //定义一数组 
			strs=this.obj.dataChildKey.split("."); //字符分割 
			var dataArray = '';
			for (var i = 0; i < strs.length; i++) {
				dataArray += '['+[i]+']';
			}
			dataArray = dataArray;
		}
		
        if(dataArray[this.obj.dataChildKey] && this.obj.dataChildKey) {
        	dataArray = dataArray[this.obj.dataChildKey];
        }
		
        //检测是否有转换
        if(this.obj.formatKey) {
            var newDataArray = [];
            for(var key in dataArray) {
                var one = {};
                one[this.obj.formatKey] = key;
                one.list = dataArray[key];
                newDataArray.push(one);
            }
            dataArray = newDataArray;
            if(this.obj.dataChildKey) {
                ret.data[this.obj.dataChildKey] = newDataArray;
            } else {
                ret.data = newDataArray;
            }
            // console.log("formatJSON:"+JSON.stringify(dataArray));
        }
		
        var renderBoxObj = this.obj.renderBox ? $(this.obj.renderBox) : $("#list-box");
        if(!dataArray.hasOwnProperty('length') || !this.pageHas) {
            this.result = false;
        } else {
            var length = dataArray.length;
			// console.log("dataJSON:"+JSON.stringify(ret));
			ret.page = this.page;
            if(this.page <= 1) {
                if(length == 0) {
					var F_Account = api.getPrefs({
									   sync: true,
									   key: 'F_Account'
									});
					// API.getStorage('F_Account');
					try{
						if(this.obj.frome == 'study' && F_Account == '13335111218'){
							var html = '<div class="list">\
											<div class="list-left">\
												<div class="name">邹莉芳</div>\
												<div class="dec">正在学习倒车入库</div>\
											</div>\
											<div class="list-right">\
												<div class="tell" data-tel = "13335111218">联系学员</div>\
											</div>\
										</div>\
										<div class="list">\
											<div class="list-left">\
												<div class="name">郝英豪</div>\
												<div class="dec">正在学习侧方位停车</div>\
											</div>\
											<div class="list-right">\
												<div class="tell" data-tel = "15665726317">联系学员</div>\
											</div>\
										</div>\
										<div class="list">\
											<div class="list-left">\
												<div class="name">姚子芸</div>\
												<div class="dec">正在学习倒车入库</div>\
											</div>\
											<div class="list-right">\
												<div class="tell" data-tel = "13335111218">联系学员</div>\
											</div>\
										</div>';
							renderBoxObj.html(html);
						}else{
							renderBoxObj.html(this.obj.emptyHtml);
						}
					}catch(e){
						//TODO handle the exception
						renderBoxObj.html(this.obj.emptyHtml);
					}
					
                } else if(length < this.obj.pageSize){
                    renderBoxObj.html( this.obj.render(ret) );
                } else {
                    renderBoxObj.html( this.obj.render(ret) );
                    this.result = true;
                }
            } else {
                if(length == this.obj.pageSize) {
                    renderBoxObj.append( this.obj.render(ret) );
                    this.result = true;
                } else {
                    renderBoxObj.append( this.obj.render(ret) );
                }
            }
			if(this.page == 1 && this.obj.isCallback == 'one'){
				if(this.obj.success) {
					$.isFunction(this.obj.success) && this.obj.success(ret);
				}
			}else if(this.obj.isCallback == 'all'){
				if(this.obj.success) {
					$.isFunction(this.obj.success) && this.obj.success(ret);
				}
			}
        }
        if(this.result==true) {
            this.page++;
        } else {
            this.pageHas=false;
        }
    },
    listenHeaderRefresh: function() {
        var that = this;
        API.refreshHeader(function() {
            that.obj.headRefresh = 1;
            that.resetData();
        });
    },
    resetData:function() {
		if(!this.isscrolltobottom && this.reset){
			this.page = 1;
			this.pageHas = true;
			this.reset = false;
			this.getData();
		}else{
			REFRESH.cancelLoading(); //隐藏下拉刷新
			// API.errorToast("刷新失败，请稍后再试");
		}
    },
    resetParam: function(key,value) {
		var that = this;
        //if(typeof key!='string' || typeof value!='string' || !key) {	// || !value
        if(typeof key!='string' || !key) {    // 20200327修改
            return this;
        }
		this.obj.params[key] = value;
		that.resetData();
        return this;
    },
    //更换模板，用于切换类型模板不一致
    resetTpl: function(tpl) {
        if(tpl) {
            this.obj.render = tpl;
        }
        return this;
    }
}